﻿using LJX.SmartPark.Common.Extensions;
using LJX.SmartPark.Common.ResponseOutput;
using LJX.SmartPark.Domain.SafeManage;
using LJX.SmartPark.EntityFramework;
using LJX.SmartPark.Service.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LJX.SmartPark.Service.SafeManage
{
    public class PatroldetailService : IPatroldetailService
    {
        private readonly IRepository<Patroldetail> _studentService;

        private readonly StudentServerContext _context;
        
        public PatroldetailService(IRepository<Patroldetail> studentService, StudentServerContext context)
        {
            _studentService = studentService;
            _context = context;
        }

        public List<Patroldetail> GetIdPatroldetail(Patrolpath input)
        {
            var result = _studentService.GetListQuery().Where(x => x.LineId == input.Id).ToList();
            return result;
        }

        private async Task<Response<bool>> PostPatroldetail(Patroldetail input)
        {
            var result = _studentService.InsertAsyncById(input.MapTo<Patroldetail>());

            return Response<bool>.Ok(result.Result > 0);
        }

        private int DeleteAllAsync(List<Patroldetail> input)
        {
            _context.RemoveRange(input);
            return _context.SaveChanges();
        }

        public bool PostAddPatroldetail(patroldetail input)
        {
            int count = 0;
            List<Patroldetail> list = _studentService.GetListQuery().Where(x => x.LineId == input.lineid).ToList();
            if (list.Count == 0)
            {
                foreach (var item in input.houseid)
                {
                    Patroldetail rm = new Patroldetail();
                    rm.LineId = input.lineid;
                    rm.HouseId = Convert.ToInt32(item);
                    PostPatroldetail(rm);
                    count++;
                }
                Patrolpath pc = _context.Patrolpath.FirstOrDefault(x => x.Id == input.lineid);
                pc.Sum = count;
                _context.Update(pc);
                _context.SaveChanges();
                return count > 0;
            }
            else
            {
                DeleteAllAsync(list);
                foreach (var item in input.houseid)
                {
                    Patroldetail rm = new Patroldetail();
                    rm.LineId = input.lineid;
                    rm.HouseId = Convert.ToInt32(item);
                    PostPatroldetail(rm);
                    count++;
                }
                Patrolpath pc = _context.Patrolpath.FirstOrDefault(x => x.Id == input.lineid);
                pc.Sum = count;
                _context.Update(pc);
                _context.SaveChanges();
                return count > 0;
            }
        }
    }
}
